package org.spring.aicloud.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.spring.aicloud.utils.MinIoUtil;
import org.spring.aicloud.utils.NameUtil;
import org.spring.aicloud.utils.ResponseEntity;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author yexiebao
 * @date 2025/5/7
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Resource
    private MinIoUtil  minIoUtil;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 创建验证码
     * @return
     */
    @RequestMapping("/create")
    public ResponseEntity create(HttpServletRequest request) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String url = "";
        //创建验证码,定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120,40);
        //设置图形验证码存入minio的名称
        String fileName = NameUtil.getCaptchaName(request);
        //将图形验证码转换成字节流
        //但是要关闭流，所以要放入try中，否则会影响流的关闭
        try(InputStream inputStream = new ByteArrayInputStream(lineCaptcha.getImageBytes())){
            //上传到miniod
            url = minIoUtil.upload(fileName, inputStream, "image/png");
            String code = lineCaptcha.getCode();
            redisTemplate.opsForValue().set(fileName, code);
        }
        return ResponseEntity.ok(url);
    }
}